// 创建用户相关的小仓库
import { defineStore } from 'pinia'

// 引入userApi接口
import { reqLogin, reqUserInfo, reqLogout } from '@/api/user'
import type { UserState } from './types/type'
import { storage } from '@/utils/storage'

// 引入路由(常量路由)
import { constantRouter } from '@/router/router'
import { useRouter } from 'vue-router'
import type { loginFormData, loginResponseData, userInfoResponseData } from '@/api/user/type'

let useUserStore = defineStore('User', {
  // 数据存储
  state: (): UserState => {
    return {
      token: storage.get('Token'),
      // 仓库存储生菜菜单数组(路由数组)
      menuRoutes: constantRouter,
      // 用户名称
      username: '',
      // 用户头像
      avatar: '',
    }
  },
  // 处理数据 异步相关
  actions: {
    // 用户登录
    async userLogin(data: loginFormData) {
      let res: loginResponseData = await reqLogin(data)
      if (res.code == 200) {
        this.token = res.data
        // 本地存储 持久化token
        storage.set('Token', res.data)
        // 能保证当前async返回一个成功的promise
        return 'ok'
      } else {
        return Promise.reject(new Error(res.data))
      }
    },
    // 获取用户信息
    async userInfo() {
      let res: userInfoResponseData = await reqUserInfo()
      if (res.code == 200) {
        this.username = res.data.name
        this.avatar = res.data.avatar
        return res.data
      } else {
        return Promise.reject(new Error(res.message))
      }
    },
    // 退出登录
    async userLogout() {
      let res = await reqLogout()
      if(res.code == 200){
        this.token = ''
        this.username = ''
        this.avatar = ''
        storage.remove('Token')
        return 'ok'
      }else{
        return Promise.reject(new Error(res.message))
      }
    },
  },
  // 获取数据
  getters: {},
})

// 对外暴露用户的小仓库
export default useUserStore
